#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

#define NUM_THREADS 10
#define DEVICE "/dev/mutex_example"
#define BUFFER_SIZE 1024

// 全局变量，用于存储文件描述符
int fd;

// 线程函数：写操作
void* write_thread(void* arg)
{
    int thread_id = *(int*)arg;
    char write_buffer[BUFFER_SIZE];
    snprintf(write_buffer, BUFFER_SIZE, "Hello from thread %d!", thread_id);

    if (write(fd, write_buffer, strlen(write_buffer)) < 0)
    {
        perror("Failed to write to device");
        return (void*)EXIT_FAILURE;
    }

    printf("Thread %d: Data written to device: %s\n", thread_id, write_buffer);
    return (void*)EXIT_SUCCESS;
}

// 线程函数：读操作
void* read_thread(void* arg)
{
    int thread_id = *(int*)arg;
    char read_buffer[BUFFER_SIZE] = {0};

    if (read(fd, read_buffer, BUFFER_SIZE) < 0)
    {
        perror("Failed to read from device");
        return (void*)EXIT_FAILURE;
    }

    printf("Thread %d: Data read from device: %s\n", thread_id, read_buffer);
    return (void*)EXIT_SUCCESS;
}

int main()
{
    pthread_t write_threads[NUM_THREADS];
    pthread_t read_threads[NUM_THREADS];
    int thread_ids[NUM_THREADS];

    // 打开设备文件
    fd = open(DEVICE, O_RDWR);
    if (fd < 0)
    {
        perror("Failed to open device");
        return EXIT_FAILURE;
    }

    printf("Device opened successfully\n");

    // 创建写线程
    for (int i = 0; i < NUM_THREADS; i++)
    {
        thread_ids[i] = i;
        if (pthread_create(&write_threads[i], NULL, write_thread, &thread_ids[i]) != 0)
        {
            perror("Failed to create write thread");
            close(fd);
            return EXIT_FAILURE;
        }
    }

    // 等待写线程完成
    for (int i = 0; i < NUM_THREADS; i++)
    {
        if (pthread_join(write_threads[i], NULL) != 0)
        {
            perror("Failed to join write thread");
            close(fd);
            return EXIT_FAILURE;
        }
    }

    // 创建读线程
    for (int i = 0; i < NUM_THREADS; i++)
    {
        if (pthread_create(&read_threads[i], NULL, read_thread, &thread_ids[i]) != 0)
        {
            perror("Failed to create read thread");
            close(fd);
            return EXIT_FAILURE;
        }
    }

    // 等待读线程完成
    for (int i = 0; i < NUM_THREADS; i++)
    {
        if (pthread_join(read_threads[i], NULL) != 0)
        {
            perror("Failed to join read thread");
            close(fd);
            return EXIT_FAILURE;
        }
    }

    // 关闭设备文件
    close(fd);
    printf("Device closed successfully\n");

    return EXIT_SUCCESS;
}